package com.yiboshi.rehrs.controller;

import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.yiboshi.rehrs.domain.entity.RechargeCard;
import com.yiboshi.rehrs.domain.entity.ZhongUser;
import com.yiboshi.rehrs.domain.entity.ZhongUserImage;
import com.yiboshi.rehrs.domain.service.IRechargeCardService;
import com.yiboshi.rehrs.domain.service.IZhongUserImageService;
import com.yiboshi.rehrs.domain.service.IZhongUserService;
import com.yiboshi.rehrs.exception.ZhongException;
import com.yiboshi.rehrs.helper.RedisHelper;
import com.yiboshi.rehrs.helper.RedisLocker;
import com.yiboshi.rehrs.manager.IptablesManager;
import com.yiboshi.rehrs.manager.ZhongYouManager;
import com.yiboshi.rehrs.param.ZhongRes;
import com.yiboshi.rehrs.util.*;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author jack 2025/4/1
 */

@Slf4j
@RestController
@RequestMapping("/system/")
public class SystemController {


    @Autowired
    ZhongYouManager zhongYouManager;

    @Autowired
    IZhongUserService zhongUserService;

    @Autowired
    IRechargeCardService rechargeCardService;

    @Autowired
    RedisHelper redisHelper;

    @Autowired
    IZhongUserImageService zhongUserImageService;

    @Autowired
    RedisLocker redisLocker;





    //登录
    @ApiOperation(value = "1.0 查询", httpMethod = "POST", notes = "1.0 添加用户", consumes = MediaType.APPLICATION_JSON_VALUE)
    @GetMapping("user/info")
    public ZhongRes<ZhongUser> userInfo(@RequestParam(value = "account") String account, HttpServletRequest request){
        if(StrUtils.isBlank(account)||account.length()<6|| !NumberUtil.isNumber(account)){
            return ZhongRes.fail("用户名不正确");
        }
        String ipAddress = WebUtils.getIpAddress(request);
        redisHelper.addIp(ipAddress);
        ZhongUser one = zhongUserService.one(account);
        String mark = "";
        if(one!=null){
            mark = "已到期";
            LocalDateTime vipExpDate = one.getVipExpDate();
            LocalDateTime now = LocalDateTime.now();
            if(vipExpDate!=null&&vipExpDate.isAfter(now)){
                int dayDiff = DateUtils.getDayDiff(now, vipExpDate);
                mark = "还有"+dayDiff+"天到期";
            }
        }


        ZhongRes ok = ZhongRes.ok(new ZhongUser());
        //mark = "";
        ok.setMsg(mark);
        return ok;
    }
    //登录
    @ApiOperation(value = "1.0 添加用户", httpMethod = "POST", notes = "1.0 添加用户", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("user/init")
    public ZhongRes addUser(@RequestBody ZhongUserImage zhongUserImage, HttpServletRequest request){
        String key = "System-addUser";
        boolean lock = redisLocker.tryLock(key, 10);
        if(!lock){
            //锁未获取 防重复
            return ZhongRes.fail("重复提交，等几秒后再试");
        }
        String ipAddress = WebUtils.getIpAddress(request);
        redisHelper.addIp(ipAddress);
        String account = zhongUserImage.getAccount();
        if(StrUtils.isBlank(account)){
            return ZhongRes.fail("用户名不正确");
        }

        ZhongUser  zhongUser =  new ZhongUser();

        zhongUser.setAccount(account);
        Integer autoTaskType = zhongUserImage.getAutoTaskType();
        Integer autoStatus = null;
        if(autoTaskType==null){
            //0-不开启、1-全部约、2-只约1和8
            autoTaskType = 2;
            autoStatus = 0;
            zhongUserImage.setAutoTaskType(autoTaskType);
        }
        if(autoTaskType>2||autoTaskType<0){
            return ZhongRes.fail("自动预约类型不正确");
        }
        if(autoStatus==null&&autoTaskType>0){
            autoStatus = 1;
        }else if(autoTaskType==0){
            //关闭自动约
            autoStatus = 0;
            autoTaskType = 2;
        }
        String image = zhongUserImage.getImage();
        String imei = zhongUserImage.getImei();
        String androidId = zhongUserImage.getAndroidId();
        String kami = zhongUserImage.getKami();
        if(StrUtils.isBlank(image)&&StrUtils.isBlank(imei)&&StrUtils.isBlank(androidId)&&StrUtils.isNotBlank(kami)){
            //只充值
            return chargeZhongRes(account, kami, autoStatus, autoTaskType);

        }


        String addUserKey = "addUser:"+account;
        Boolean cache = CacheUtils.getByCache10Hour(addUserKey, Boolean.class);
        if(cache==null){
            cache = StrUtils.isNotBlank(redisHelper.loadTaskToken(account));
           if(cache){
               CacheUtils.putByCache10Hour(addUserKey, true);
           }
        }
        ZhongUser userDB = zhongUserService.getOne(account, 0);
        if(StrUtils.isBlank(image)&&StrUtils.isBlank(imei)&&StrUtils.isBlank(androidId)&&Objects.equals(cache,true)){

        }else{
            boolean imageDB = false;
            if(StrUtils.isBlank(image)){
                ZhongUserImage zhongUserImageDB = zhongUserImageService.getOne(account);
                image = zhongUserImageDB==null?"":zhongUserImageDB.getImage();
                imageDB =  zhongUserImageDB!=null;
            }

            if(StrUtils.isBlank(imei)){
                imei = userDB==null?"":userDB.getImei();
            }

            if(StrUtils.isBlank(androidId)){
                androidId = userDB==null?"":userDB.getAndroidId();
            }
            imei = imei==null?"":imei.replace("IMEI:","");
            androidId = androidId==null?"":androidId.replace("AndroidId:","");
            if(imei.equals("867382035888381")){
                //默认imei不支持登记
                imei = "";
            }
            if(StrUtils.isBlank(androidId)&&StrUtils.isBlank(imei)){
                return ZhongRes.fail("设备注册号码不能为空");
            }
        /*if(StrUtils.isBlank(image)||StrUtils.isBlank(imei)){
            return ZhongRes.fail("图片或者设备注册号码不能为空");
        }*/
       /* LambdaQueryWrapper<ZhongUser> queryWrapper = zhongUserService.getQueryWrapper().eq(ZhongUser::getImei, imei)
                .eq(ZhongUser::getMode, 0)
                .ne(ZhongUser::getAccount,account)
                ;
        int count = zhongUserService.count(queryWrapper);
        if(count>0){
            return ZhongRes.fail("设备注册号码已经存在");
        }*/
            log.info("image length:{}",image.length());
            if(!imageDB){
                image = ThumbnailatorUtils.compressBase64Image(image,0.8);
            }

            if(StrUtils.isBlank(image)){
                return ZhongRes.fail("图片不正确");
            }
            log.info("compressBase64Image length:{}",image.length());
            zhongUserImage.setImage(image);
            //351564710852443
            //869296041015581
            zhongUser.setPadId(imei);
            zhongUser.setImei(imei);
            zhongUser.setAndroidId(androidId);
            zhongUser.setInitIp(ipAddress);

            Pair<ZhongUser, String> stringStringPair = null;
            String message = "";
            try{
                stringStringPair = zhongYouManager.logonByFace(zhongUser, image);
                message = stringStringPair.getValue();
            }catch (ZhongException e){
                message = e.getMessage();
            }
            message = message==null?"":message;
            message= message.replace("登录","验证");
            if(message.contains("非常规工作地点")){
                message = "设备注册号码不正确";
            }
            String token = zhongUser.getToken();
            boolean fail = StrUtils.isBlank(token);
            if(fail){
                return ZhongRes.fail(message);
            }
            CacheUtils.putByCache10Hour(account,true);
            //0-不开启、1-全部约、2-只约1和8
            zhongUser.setAutoStatus(autoStatus);
            zhongUser.setAutoTaskType(autoTaskType);
            zhongUser.setMode(0);
            zhongUserService.saveOrUpdateUserFace(zhongUser,zhongUserImage);
            userDB = zhongUser;
        }
        //zhongUser = zhongUserService.getOne(account, 0);
        if(userDB==null){
            userDB = zhongUserService.getOne(account, 0);
        }
        if(userDB==null){
            return ZhongRes.fail("该用户不存在");
        }
        LocalDateTime vipExpDate = userDB.getVipExpDate();
        if(vipExpDate==null){
            vipExpDate = LocalDateTime.now();
        }
        String tip = account+"到期时间"+DateUtils.dateTimeToStr(vipExpDate,DateUtils.CH_TIME)+"。";
        if(StrUtils.isBlank(kami)){
            return ZhongRes.fail(tip+CommonUtil.buildTaskType(zhongUser.getAutoStatus(),zhongUser.getAutoTaskType()));
        }
        //获取卡密数据
        RechargeCard one = rechargeCardService.getOne(kami);
        if(one==null){
            return ZhongRes.fail("卡密无效或者已经使用,"+tip);
        }
        if(Objects.equals(one.getVipAcount(),account)){
            //自己使用的就可以更新autoTaskType
            userDB.setAutoStatus(autoStatus);
            userDB.setAutoTaskType(autoTaskType);
            userDB.setVipExpDate(null);
           //更新type 已使用
           zhongUserService.updateById(userDB);
           redisHelper.delSessionUser(userDB.getAccount());
            return ZhongRes.fail(tip+CommonUtil.buildTaskType(autoStatus,userDB.getAutoTaskType()));
        }
        if(one.getUsedStatus().equals(1)){
            return ZhongRes.fail("卡密无效或者已经使用");
        }
        userDB.setAutoStatus(autoStatus);
        userDB.setAutoTaskType(autoTaskType);
        int exchange = rechargeCardService.exchange(one, userDB);
        if(exchange==0){
            return ZhongRes.fail("卡密无效或者已经使用,刷新后重试");
        }
        if(exchange==2){
            return ZhongRes.fail("该账号已试用，无法再次试用");
        }
        //检查卡密状态
        //更新VIP时间
        ZhongRes ok = ZhongRes.ok();
        vipExpDate = userDB.getVipExpDate();
        ok.setMsg(account+"登记成功,到期时间"+DateUtils.dateTimeToStr(vipExpDate,DateUtils.CH_TIME)+CommonUtil.buildTaskType(autoStatus,userDB.getAutoTaskType()));
        redisHelper.delSessionUser(userDB.getAccount());
        return ok;
    }

    @NotNull
    private ZhongRes chargeZhongRes(String account, String kami, Integer autoStatus, Integer autoTaskType) {
        //只是续费
        ZhongUser userDB = zhongUserService.getOne(account, 0);
        if(userDB==null){
            return ZhongRes.fail("用户不存在");
        }
        //获取卡密数据
        RechargeCard one = rechargeCardService.getOne(kami);
        if(one==null){
            return ZhongRes.fail("卡密无效或者已经使用");
        }
        userDB.setAutoStatus(null);
        userDB.setAutoTaskType(null);
        int exchange = rechargeCardService.exchange(one, userDB);
        if(exchange==0){
            return ZhongRes.fail("卡密无效或者已经使用,刷新后重试");
        }
        if(exchange==2){
            return ZhongRes.fail("该账号已试用，无法再次试用");
        }
        ZhongRes ok = ZhongRes.ok();
        LocalDateTime vipExpDate = userDB.getVipExpDate();
        ok.setMsg(account +"登记成功,到期时间"+DateUtils.dateTimeToStr(vipExpDate,DateUtils.CH_TIME)+CommonUtil.buildTaskType(autoStatus,userDB.getAutoTaskType()));
        redisHelper.delSessionUser(userDB.getAccount());
        return ok;
    }


    @ApiOperation(value = "1.0 发卡", httpMethod = "POST", notes = "1.0 发卡", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("admin/card")
    public ZhongRes  adminCard(@RequestBody JSONObject jsonObject){
        String auth = jsonObject.getString("auth");
        LocalDate now = LocalDate.now();
        String today = DateUtils.dateToStr(now, DateUtils.DATE_DAY);
        today = today+today.substring(today.length()-2);
        if(!today.equals(auth)){
            return ZhongRes.ok();
        }

        String agentAccount = jsonObject.getString("agentAccount");
        Integer total = jsonObject.getInteger("num");
        Integer vipDays = jsonObject.getInteger("vipDays");
        total = total==null?1:total;
        int i = 1;
        int cardType = jsonObject.getInteger("type");;//0试用 1正式
        if(cardType==0){
            vipDays = 1;
        }
        String key = "card_"+agentAccount+"_"+total+"_"+cardType+"_"+vipDays;
        boolean lock = redisLocker.tryLock(key, 20);
        if(!lock){
            //锁未获取 防重复
            return ZhongRes.ok("");
        }
        //String account = "2153011500166";//2153011500166
        List<RechargeCard> rechargeCardList = new ArrayList<>();
        List<String> cardList = new ArrayList<>();
        while(i++<=total){
            RechargeCard entity = new RechargeCard();
            entity.setId(IdWorker.getId());
            entity.setCardNo(RechargeCardUtil.generate());
            entity.setDaysNum(vipDays);
            entity.setUsedStatus(0);
            entity.setUsedTime(null);
            entity.setCardType(cardType);
            entity.setCreateTime(LocalDateTime.now());
            entity.setAgentAccount(agentAccount);
            rechargeCardList.add(entity);
            cardList.add(entity.getCardNo());
        }
        rechargeCardService.saveBatch(rechargeCardList);
        rechargeCardService.deleteByTime();
        return ZhongRes.ok(cardList);

    }

    @ApiOperation(value = "", httpMethod = "GET", notes = "", consumes = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("channal/on_off/{mode}/{enable}")
    public ZhongRes<String> userInfo(@PathVariable Integer mode,@PathVariable Integer enable ,HttpServletRequest request){
        if(mode<=1||mode>=4){
            return ZhongRes.fail("参数错误");
        }
        if(Objects.equals(enable,0)){
            redisHelper.deleteHelper(mode+"");
        }else{
            redisHelper.addModeHelper(mode+"");
        }
        return ZhongRes.ok(mode+(Objects.equals(enable,0)?"关闭成功":"开启成功"));
    }

}
